package com.admin.service.impl;

import java.util.*;

import com.admin.common.enums.EnumIstatus;
import com.admin.common.enums.MemberLevelEnum;
import com.admin.common.exception.BizException;
import com.admin.common.util.RedisUtil;
import com.admin.domain.Region;
import com.admin.domain.RoleDO;
import com.admin.mapper.DeclareMapper;
import com.admin.req.user.MemberReq;
import com.admin.service.*;
import com.admin.vo.system.*;
import jakarta.annotation.PostConstruct;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.admin.common.enums.EnumResult;
import com.admin.common.shiro.ShiroUtils;
import com.admin.common.shiro.WebSessionManager;
import com.admin.common.util.DateUtils;
import com.admin.common.util.MD5Utils;
import com.admin.common.util.YsCollectionUtil;
import com.admin.domain.AdminDO;
import com.admin.mapper.AdminMapper;
import com.admin.mapper.AdminRoleMapper;
import com.admin.vo.PageVO;
import com.admin.vo.ResultVO;
import com.admin.vo.SimpleResultVO;

@Service
public class AdminServiceImpl extends BaseServiceImpl<AdminDO> implements AdminService {

    private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private TransactionService transactionService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private AdminMapper adminMapper;
     @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private RegionsService regionsService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeclareMapper declareMapper;
    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private CodeImageService codeImageService;

    @Autowired
    private RedisUtil redisUtil;

    @PostConstruct
    private void init() {
        setBaseMapper(adminMapper);
    }


    @Override
    public AdminInfoVO getAdminInfoVO(Integer userId) {
        AdminDO adminDO = adminMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(adminDO)) {
            throw new BizException(-1, EnumResult.USER_DATA_NULL.getMsg());
        }
        RoleDO roleDO = roleService.findRoleLevelByUserId(adminDO.getUserId());
        if (Objects.isNull(roleDO)) {
            throw new BizException(-1, "该用户还未分配角色，请联系管理员!");
        }

        AdminInfoVO adminInfoVO = new AdminInfoVO();
        BeanUtils.copyProperties(adminDO, adminInfoVO);
        adminInfoVO.setUserId(adminDO.getUserId());
        //角色等级
        adminInfoVO.setRoleLevel(roleDO.getRoleLevel());
        adminInfoVO.setResponsibleArea(roleDO.getResponsibleArea());
        adminInfoVO.setResponsibleAreaId(roleDO.getResponsibleAreaId());
        return adminInfoVO;
    }

    @Override
    public ResultVO<AdminLoginVO> login(String username, String password, String code, String uuid) {
        ResultVO<AdminLoginVO> result = new ResultVO<>();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || Objects.isNull(code) || Objects.isNull(uuid)) {
            result.setCode(EnumResult.PARAM_NULL.getCode());
            result.setMsg(EnumResult.PARAM_NULL.getMsg());
            return result;
        }
        //校验验证码是否正常
        boolean checkCode = codeImageService.validateCaptcha(code, uuid);
        if (!checkCode) {
            result.setCode(-1);
            result.setMsg("验证码输入错误,请重新输入!");
            return result;
        }

        String redisLoginErrorKey = "login_error_" + username;
        //校验登录失败次数
        Integer errorNum = (Integer) redisUtil.get(redisLoginErrorKey);
        if (Objects.nonNull(errorNum) && errorNum >3) {
            result.setCode(-1);
            result.setMsg("登录失败已超过3次,请10分钟后重试！");
            return result;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            Subject subject = SecurityUtils.getSubject();
            ShiroUtils.clearCachedAuthorization(username);
            subject.login(token);

            AdminLoginVO adminLoginVO = new AdminLoginVO();
            adminLoginVO.setToken(subject.getSession().getId().toString());

            AdminInfoVO adminInfoVO = new AdminInfoVO();
            AdminDO adminDO = adminMapper.selectByPrimaryKey(ShiroUtils.getUserId());
            BeanUtils.copyProperties(adminDO, adminInfoVO);
            adminLoginVO.setAdminInfoVO(adminInfoVO);

            ResultVO<List<String>> r = menuService.getCanSeeMenuPerms(ShiroUtils.getUserId());
            MenuPermCanSeeVO menuPermCanSeeVO = new MenuPermCanSeeVO();
            menuPermCanSeeVO.setMenuPerms(r.getData());
            adminLoginVO.setMenuPermCanSeeVO(menuPermCanSeeVO);

            result.setData(adminLoginVO);
            result.setCode(EnumResult.SUCCESS.getCode());
            result.setMsg(EnumResult.SUCCESS.getMsg());

            redisUtil.del(redisLoginErrorKey);
        } catch (Exception e) {
            //记录失败次数
            Long errorNums = redisUtil.increase(redisLoginErrorKey, 1L);
            //设置失效时间 - 10分钟
            redisUtil.set(redisLoginErrorKey, errorNums, 10 * 60);

            logger.error(e.getMessage());

            result.setCode(EnumResult.USER_LOGIN_PASSWORD_ERROR.getCode());
            result.setMsg(EnumResult.USER_LOGIN_PASSWORD_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 剔除此账号在其它地方的登录(redis模糊搜索session缓存的key，redis会出现慢日志有性能问题，去掉)
     * 
     * @param currentUser
     */
    @SuppressWarnings("unused")
	@Deprecated
    private void removeOtherLoginedSession(Subject currentUser) {
        AdminDO loginUser = (AdminDO)currentUser.getPrincipal();
        WebSessionManager sessionManager =
            (WebSessionManager)((DefaultSecurityManager)SecurityUtils.getSecurityManager()).getSessionManager();
        Collection<Session> list = sessionManager.getSessionDAO().getActiveSessions();
        for (Session session : list) {
            Subject s = new Subject.Builder().session(session).buildSubject();
            if (s.isAuthenticated()) {
                AdminDO user = (AdminDO)s.getPrincipal();
                if (user.getUsername().equals(loginUser.getUsername())) {
                    // 不是该用户最新的sessionId，就删除其它已登录的session
                    if (!session.getId().equals(currentUser.getSession().getId())) {
                        sessionManager.getSessionDAO().delete(session);
                    }
                }
            } else {
                // 不是登陆成功产生的sessionId，也删除
                sessionManager.getSessionDAO().delete(session);
            }
        }
    }

    @Override
    public SimpleResultVO deleteByPrimaryKeys(List<Integer> list) {
        SimpleResultVO result = new SimpleResultVO();
        if (CollectionUtils.isEmpty(list)) {
            result.setCode(EnumResult.PARAM_NULL.getCode());
            result.setMsg(EnumResult.PARAM_NULL.getMsg());
            return result;
        }
        transactionService.deleteAdmins(list);
        ShiroUtils.clearAllCachedAuthorization();

        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }

    @Override
    public SimpleResultVO deleteByPrimaryKey(Integer userId) {
        SimpleResultVO result = new SimpleResultVO();
        if (userId == null || userId == 0) {
            result.setCode(EnumResult.PARAM_NULL.getCode());
            result.setMsg(EnumResult.PARAM_NULL.getMsg());
            return result;
        }
        transactionService.deleteAdmin(userId);
        ShiroUtils.clearAllCachedAuthorization();
        return SimpleResultVO.ok();
    }

    @Override
    public ResultVO<PageVO<ListAdminVO>> getPageList(Integer pageIndex, Integer pageSize, Map<String, Object> params) {
        ResultVO<PageVO<ListAdminVO>> result = new ResultVO<>();
        PageVO<ListAdminVO> page = new PageVO<>(pageIndex, pageSize);
        List<ListAdminVO> adminVOs = new ArrayList<>();

        // 查询管理员总数
        Integer totalCount = adminMapper.countByMap(params);
        page.setTotalCount(totalCount);
        if (totalCount > 0) {
            // 查询管理员信息
            params.put("startIndex", page.getStartIndex());
            params.put("pageSize", page.getPageSize());
            List<AdminDO> adminDOs = adminMapper.selectByMap(params);
            adminVOs = YsCollectionUtil.copyList(adminDOs, ListAdminVO.class);
            List<Integer> userIds = new ArrayList<>();
            for (ListAdminVO adminVO : adminVOs) {
                userIds.add(adminVO.getUserId());
            }
            params.clear();
            // 查询管理员角色信息
            params.put("userIds", userIds);
            List<AdminRoleVO> adminRoleVOs = adminRoleMapper.selectVOByMap(params);
            Map<Integer, List<String>> adminRoleNamesMap = new HashMap<Integer, List<String>>();
            for (AdminRoleVO adminRoleVO : adminRoleVOs) {
                if (adminRoleNamesMap.containsKey(adminRoleVO.getUserId())) {
                    List<String> roleNames = adminRoleNamesMap.get(adminRoleVO.getUserId());
                    roleNames.add(adminRoleVO.getRoleName());
                    adminRoleNamesMap.put(adminRoleVO.getUserId(), roleNames);
                } else {
                    List<String> roleNames = new ArrayList<>();
                    roleNames.add(adminRoleVO.getRoleName());
                    adminRoleNamesMap.put(adminRoleVO.getUserId(), roleNames);
                }
            }
            for (ListAdminVO adminVO : adminVOs) {
                adminVO.setAddTimeStr(DateUtils.formatDate(adminVO.getCreateTime()));
                adminVO.setRoleNames(adminRoleNamesMap.get(adminVO.getUserId()));
                adminVO.setIstatusName(EnumIstatus.getText(adminVO.getIstatus()));
            }
        }
        page.setData(adminVOs);
        result.setData(page);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @Override
    public SimpleResultVO updatePassWord(String username, String oldPassword, String newPassword,
        String confirmPassword) {
        SimpleResultVO result = new SimpleResultVO();
        if (Objects.isNull(oldPassword)) {
            throw new BizException(-1, "请输入旧密码!");
        }

        if (Objects.isNull(newPassword)) {
            throw new BizException(-1, "请输入新密码");
        }

        if (Objects.isNull(confirmPassword)) {
            throw new BizException(-1, "请输入确认密码!");
        }

        if (!confirmPassword.equals(newPassword)) {
            throw new BizException(-1, EnumResult.USER_CHANGE_PASSWORD_DIFF.getMsg());
        }

        AdminDO adminDO = adminMapper.selectByPrimaryKey(ShiroUtils.getUserId());
        if (Objects.isNull(adminDO)) {
            throw new BizException(-1, EnumResult.USER_DATA_NULL.getMsg());
        }
        //验证旧密码
//        oldPassword = MD5Utils.string32MD5(oldPassword + MD5Utils.USER_PWD_SUFFIX);
        if (!oldPassword.equals(adminDO.getPassword())) {
            throw new BizException(-1, EnumResult.USER_CHANGE_PASSWORD_OLD_ERROR.getMsg());
        }

//        newPassword = MD5Utils.string32MD5(newPassword + MD5Utils.USER_PWD_SUFFIX);
        AdminDO updateAdmin = new AdminDO();
        updateAdmin.setUserId(adminDO.getUserId());
        updateAdmin.setPassword(newPassword);
        updateAdmin.setIsResetPassword(1);
        adminMapper.updateByPrimaryKeySelective(updateAdmin);

        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }

    @Override
    public Boolean resetPassWord(Integer userId) {
        AdminDO adminDO = adminMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(adminDO)) {
            throw new BizException(-1, EnumResult.USER_NOT_LOGIN.getMsg());
        }
        AdminDO updateAdmin = new AdminDO();
        updateAdmin.setUserId(adminDO.getUserId());
        updateAdmin.setPassword(MD5Utils.string32MD5("123456" + MD5Utils.USER_PWD_SUFFIX));
        adminMapper.updateByPrimaryKeySelective(updateAdmin);
        return true;
    }

    /**
     * checked
     *
     * @param adminDO
     * @param roleIds
     * @return
     */
    @Override
    public SimpleResultVO saveAdminDO(AdminDO adminDO, List<Long> roleIds) {
        SimpleResultVO result = new SimpleResultVO();
        if (CollectionUtils.isEmpty(roleIds)) {
            throw new BizException(-1, "请选择角色!");
        }
        if (StringUtils.isEmpty(adminDO.getResponsibleAreaIds())) {
            throw new BizException(-1, "请选择负责地区!");
        }
        if (adminMapper.selectByUsername(adminDO.getUsername()) != null) {
            throw new BizException(EnumResult.USER_CREATE_FAIL_USERNAME_EXISTS.getCode(), EnumResult.USER_CREATE_FAIL_USERNAME_EXISTS.getMsg());
        }
        adminDO.setRole(0);
//        adminDO.setPassword(MD5Utils.string32MD5(adminDO.getPassword() + MD5Utils.USER_PWD_SUFFIX));
        adminDO.setPassword(adminDO.getPassword());
        if (adminDO.getMemberLevel().equals(MemberLevelEnum.PROVINCE.getKey())) {
            adminDO.setBusinessAreaIds(adminDO.getResponsibleAreaIds());
        } else if (adminDO.getMemberLevel().equals(MemberLevelEnum.CITY.getKey())
                || adminDO.getMemberLevel().equals(MemberLevelEnum.AREA.getKey())) {
            //市用户 区县
            StringBuffer areaBuffer = new StringBuffer();
            String[] areaIds = adminDO.getResponsibleAreaIds().split(",");
            for (String areaId : areaIds) {
                if (StringUtils.isEmpty(areaId)) {
                    continue;
                }
                String[] areaArrayIds = areaId.split("-");
                String last = areaArrayIds[areaArrayIds.length - 1];
                areaBuffer.append(last).append(",");
            }
            adminDO.setBusinessAreaIds(areaIds[areaIds.length - 1]);
            adminDO.setResponsibleArea(regionsService.getNameByIds(adminDO.getBusinessAreaIds()));
        }
        transactionService.saveAdminDO(adminDO, roleIds);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }



    /**
     * 新增- 申报用户
     * @param memberReq
     * @return
     */
    @Override
    public SimpleResultVO saveMember(MemberReq memberReq) {
        SimpleResultVO result = new SimpleResultVO();
        if (memberReq == null) {
            result.setCode(EnumResult.PARAM_NULL.getCode());
            result.setMsg(EnumResult.PARAM_NULL.getMsg());
            return result;
        }

        if (CollectionUtils.isEmpty(memberReq.getRoleIds())) {
            throw new BizException(-1, "请选择用户权限!");
        }


        if (StringUtils.isEmpty(memberReq.getRegionIds())) {
            throw new BizException(-1, "请选择市/区县/乡镇");
        }

        if (adminMapper.selectByUsername(memberReq.getUsername()) != null) {
            throw new BizException(-1,EnumResult.USER_CREATE_FAIL_USERNAME_EXISTS.getMsg());
        }

        AdminDO adminDO = new AdminDO();
        BeanUtils.copyProperties(memberReq, adminDO);
        adminDO.setRealname(adminDO.getUsername());
        adminDO.setOperatorId(ShiroUtils.getUserId());
        adminDO.setOperatorName(ShiroUtils.getUserName());
        //乡镇街道
        adminDO.setCountryId(Integer.valueOf(memberReq.getRegionIds()));
        Region countryRegion = regionsService.getByRegionId(adminDO.getCountryId());
        if (Objects.isNull(countryRegion)) {
            throw new BizException(-1, "乡镇数据异常!");
        }
        adminDO.setCountryName(countryRegion.getRegionName());

        //区县
        adminDO.setAreaId(countryRegion.getParentId());
        Region areaRegion = regionsService.getByRegionId(adminDO.getAreaId());
        if (Objects.isNull(areaRegion)) {
            throw new BizException(-1, "区数据异常!");
        }
        adminDO.setAreaName(areaRegion.getRegionName());

        //市区
        adminDO.setCityId(areaRegion.getParentId());
        Region cityRegion = regionsService.getByRegionId(adminDO.getCityId());
        if (Objects.isNull(cityRegion)) {
            throw new BizException(-1, "市数据异常!");
        }
        adminDO.setCityName(cityRegion.getRegionName());

        //省
        adminDO.setProvinceId(cityRegion.getParentId());
        Region provinceRegion = regionsService.getByRegionId(adminDO.getProvinceId());
        if (Objects.isNull(provinceRegion)) {
            throw new BizException(-1, "省数据异常!");
        }
        adminDO.setProvinceName(provinceRegion.getRegionName());


        StringBuffer regionNames = new StringBuffer();
        regionNames.append(adminDO.getProvinceName()).append("/").append(adminDO.getCityName()).append("/")
                .append(adminDO.getAreaName()).append("/").append(adminDO.getCountryName());
        adminDO.setRegionNames(regionNames.toString());

        //会员类型 0为管理员 1为普通用户
        adminDO.setRole(1);
//        adminDO.setPassword(MD5Utils.string32MD5(adminDO.getPassword() + MD5Utils.USER_PWD_SUFFIX));
        adminDO.setPassword(adminDO.getPassword());
        transactionService.saveAdminDO(adminDO, memberReq.getRoleIds());
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @Override
    public SimpleResultVO updateMember(MemberReq memberReq) {
        SimpleResultVO result = new SimpleResultVO();
        if (memberReq == null || memberReq.getUserId() == null) {
            throw new BizException(EnumResult.PARAM_NULL.getCode(), EnumResult.PARAM_NULL.getMsg());
        }
        List<Long> roleIds = memberReq.getRoleIds();
        AdminDO adminDO = new AdminDO();
        BeanUtils.copyProperties(memberReq, adminDO);
        adminDO.setRealname(adminDO.getUsername());
        adminDO.setOperatorId(ShiroUtils.getUserId());
        adminDO.setOperatorName(ShiroUtils.getUserName());
        //乡镇街道
        adminDO.setCountryId(Integer.valueOf(memberReq.getRegionIds()));
        Region countryRegion = regionsService.getByRegionId(adminDO.getCountryId());
        if (Objects.isNull(countryRegion)) {
            throw new BizException(-1, "乡镇数据异常!");
        }
        adminDO.setCountryName(countryRegion.getRegionName());

        //区县
        adminDO.setAreaId(countryRegion.getParentId());
        Region areaRegion = regionsService.getByRegionId(adminDO.getAreaId());
        if (Objects.isNull(areaRegion)) {
            throw new BizException(-1, "区数据异常!");
        }
        adminDO.setAreaName(areaRegion.getRegionName());

        //市区
        adminDO.setCityId(areaRegion.getParentId());
        Region cityRegion = regionsService.getByRegionId(adminDO.getCityId());
        if (Objects.isNull(cityRegion)) {
            throw new BizException(-1, "市数据异常!");
        }
        adminDO.setCityName(cityRegion.getRegionName());

        //省
        adminDO.setProvinceId(cityRegion.getParentId());
        Region provinceRegion = regionsService.getByRegionId(adminDO.getProvinceId());
        if (Objects.isNull(provinceRegion)) {
            throw new BizException(-1, "省数据异常!");
        }
        adminDO.setProvinceName(provinceRegion.getRegionName());

        StringBuffer regionNames = new StringBuffer();
        regionNames.append(adminDO.getProvinceName()).append("/").append(adminDO.getCityName()).append("/")
                .append(adminDO.getAreaName()).append("/").append(adminDO.getCountryName());
        adminDO.setRegionNames(regionNames.toString());

        AdminDO oldAdminDO = adminMapper.selectByPrimaryKey(memberReq.getUserId());
        if (!oldAdminDO.getPassword().equals(memberReq.getPassword())) {
//            adminDO.setPassword(MD5Utils.string32MD5(memberReq.getPassword() + MD5Utils.USER_PWD_SUFFIX));
            adminDO.setPassword(memberReq.getPassword());
        }
        List<Long> exsitsRoleIds = adminRoleMapper.getRoleIdsByUserId(adminDO.getUserId());
        List<Long> temp = new ArrayList<Long>(exsitsRoleIds);

        exsitsRoleIds.removeAll(roleIds);
        roleIds.removeAll(temp);
        adminDO.setRole(1);
        transactionService.updateAdminDO(adminDO, exsitsRoleIds, roleIds);

        if (!CollectionUtils.isEmpty(exsitsRoleIds) || !CollectionUtils.isEmpty(roleIds)) {
            ShiroUtils.clearAllCachedAuthorization();
        }
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }

    @Override
    public SimpleResultVO updateAdminDO(AdminDO adminDO, List<Long> roleIds) {
        SimpleResultVO result = new SimpleResultVO();
        if (adminDO == null || adminDO.getUserId() == null || CollectionUtils.isEmpty(roleIds)) {
            result.setCode(EnumResult.PARAM_NULL.getCode());
            result.setMsg(EnumResult.PARAM_NULL.getMsg());
            return result;
        }
        AdminDO oldAdminDO = adminMapper.selectByPrimaryKey(adminDO.getUserId());
        if (!oldAdminDO.getPassword().equals(adminDO.getPassword())) {
//            adminDO.setPassword(MD5Utils.string32MD5(adminDO.getPassword() + MD5Utils.USER_PWD_SUFFIX));
            adminDO.setPassword(adminDO.getPassword());
        }
        List<Long> exsitsRoleIds = adminRoleMapper.getRoleIdsByUserId(adminDO.getUserId());
        List<Long> temp = new ArrayList<Long>(exsitsRoleIds);

        exsitsRoleIds.removeAll(roleIds);
        roleIds.removeAll(temp);
        adminDO.setRole(0);
        //封装对应的负责区域
        if (adminDO.getMemberLevel().equals(MemberLevelEnum.PROVINCE.getKey())) {
            adminDO.setBusinessAreaIds(adminDO.getResponsibleAreaIds());
        } else if (adminDO.getMemberLevel().equals(MemberLevelEnum.CITY.getKey()) || adminDO.getMemberLevel().equals(MemberLevelEnum.AREA.getKey())) {
            //市用户 区县
            StringBuffer areaBuffer = new StringBuffer();
            String[] areaIds = adminDO.getResponsibleAreaIds().split(",");
            for (String areaId : areaIds) {
                if (StringUtils.isEmpty(areaId)) {
                    continue;
                }
                String[] areaArrayIds = areaId.split("-");
                String last = areaArrayIds[areaArrayIds.length - 1];
                areaBuffer.append(last).append(",");
            }
            adminDO.setBusinessAreaIds(areaIds[areaIds.length - 1]);
            adminDO.setResponsibleArea(regionsService.getNameByIds(adminDO.getBusinessAreaIds()));
        }
        transactionService.updateAdminDO(adminDO, exsitsRoleIds, roleIds);

        if (!CollectionUtils.isEmpty(exsitsRoleIds) || !CollectionUtils.isEmpty(roleIds)) {
            ShiroUtils.clearAllCachedAuthorization();
        }
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @Override
    public List<Integer> getResponsibleAreaIds() {
        AdminDO adminDO = adminMapper.selectByPrimaryKey(ShiroUtils.getUserId());
        if (Objects.isNull(adminDO) || StringUtils.isEmpty(adminDO.getBusinessAreaIds())) {
            throw new BizException(-1, "该用户未配置负责的区域,请确认!");
        }
        String[] responsibleAreaIdArray = adminDO.getBusinessAreaIds().split(",");
        List<Integer> areaIds = new ArrayList<>();
        for (String responsibleAreaId : responsibleAreaIdArray) {
            if (StringUtils.isEmpty(responsibleAreaId)) {
                continue;
            }
            areaIds.add(Integer.parseInt(responsibleAreaId));
        }
        return areaIds;
    }

    @Override
    public Integer getResponsibleAreaIds(Integer userId) {
        AdminDO adminDO = adminMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(adminDO) || StringUtils.isEmpty(adminDO.getBusinessAreaIds())) {
            throw new BizException(-1, "该用户未配置负责的区域,请确认!");
        }
        return Integer.valueOf(adminDO.getBusinessAreaIds());
    }

    /**
     * 统计区域下 正常申报的用户的数量
     * checked
     * @param memberLevel
     * @param regionId
     * @return
     */
    @Override
    public Integer totalUserQuantity(String memberLevel, Integer regionId) {
        Map<String,Object> params = new HashMap<>();
        params.put("currentRoundDeclareSwitch", 1);
        params.put("istatus", EnumIstatus.OK.getKey());
        if (memberLevel.equals(MemberLevelEnum.AREA.getKey())) {
            params.put("areaId", regionId);
        } else if (memberLevel.equals(MemberLevelEnum.CITY.getKey())) {
            params.put("cityId", regionId);
        } else if (memberLevel.equals(MemberLevelEnum.PROVINCE.getKey())) {
            params.put("provinceId", regionId);
        }
        return adminMapper.countByMap(params);
    }

    /**
     * 区域 本轮申报-提交上来的数量
     * checked
     * @param memberLevel
     * @param regionId
     * @return
     */
    @Override
    public Integer currentRoundDeclareQuantity(String memberLevel, Integer regionId) {
        Map<String,Object> params = new HashMap<>();
        //本来申报开始时间
        params.put("startTime", DateUtils.dateFormatStr(sysParamService.getCurrentDeclareStartTime()));
        if (memberLevel.equals(MemberLevelEnum.AREA.getKey())) {
            params.put("areaIds", Arrays.asList(regionId));
            params.put("isSubmitArea", 1);
        } else if (memberLevel.equals(MemberLevelEnum.CITY.getKey())) {
            params.put("cityIds", Arrays.asList(regionId));
            params.put("isSubmitCity", 1);
        } else if (memberLevel.equals(MemberLevelEnum.PROVINCE.getKey())) {
            params.put("provinceIds", Arrays.asList(regionId));
            params.put("isSubmitProvince", 1);
        }
        return declareMapper.countByMap(params);
    }
}
